package com.device.controller;

import com.device.dto.SubDeviceDTO;
import com.device.entity.SubDevice;
import com.device.service.SubDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Api(tags = "二级设备管理")
@RestController
@RequestMapping("/api/sub-devices")
@CrossOrigin(origins = "*")
public class SubDeviceController {
    
    @Autowired
    private SubDeviceService subDeviceService;
    
    /**
     * 根据主设备IMEI获取分设备列表
     */
    @ApiOperation(value = "获取二级设备列表", notes = "根据主设备IMEI获取二级设备列表")
    @GetMapping("/main/{mainDeviceImei}")
    public ResponseEntity<Map<String, Object>> getSubDevicesByMainImei(
            @ApiParam(value = "主设备IMEI", required = true) @PathVariable String mainDeviceImei) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<SubDevice> subDevices = subDeviceService.getSubDevicesByMainImei(mainDeviceImei);
            response.put("success", true);
            response.put("data", subDevices);
            response.put("message", "获取二级设备列表成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取二级设备列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据主设备IMEI获取分设备DTO列表（包含Modbus配置）
     */
    @ApiOperation(value = "获取二级设备列表（包含Modbus配置）", notes = "根据主设备IMEI获取二级设备列表，包含Modbus配置信息")
    @GetMapping("/main/{mainDeviceImei}/with-modbus")
    public ResponseEntity<Map<String, Object>> getSubDeviceDTOsByMainImei(
            @ApiParam(value = "主设备IMEI", required = true) @PathVariable String mainDeviceImei) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<SubDeviceDTO> subDeviceDTOs = subDeviceService.getSubDeviceDTOsByMainImei(mainDeviceImei);
            response.put("success", true);
            response.put("data", subDeviceDTOs);
            response.put("message", "获取二级设备列表（包含Modbus配置）成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取二级设备列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据ID获取分设备详情
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "获取分设备详情", notes = "根据ID获取分设备详情")
    public ResponseEntity<Map<String, Object>> getSubDeviceById(
            @ApiParam(value = "分设备ID", required = true) @PathVariable UUID id) {
        Map<String, Object> response = new HashMap<>();
        try {
            SubDevice subDevice = subDeviceService.getSubDeviceById(id);
            if (subDevice != null) {
                response.put("success", true);
                response.put("data", subDevice);
                response.put("message", "获取分设备详情成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "分设备不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取分设备详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据ID获取分设备DTO详情（包含Modbus配置）
     */
    @GetMapping("/{id}/with-modbus")
    @ApiOperation(value = "获取分设备详情（包含Modbus配置）", notes = "根据ID获取分设备详情，包含Modbus配置信息")
    public ResponseEntity<Map<String, Object>> getSubDeviceDTOById(
            @ApiParam(value = "分设备ID", required = true) @PathVariable UUID id) {
        Map<String, Object> response = new HashMap<>();
        try {
            SubDeviceDTO subDeviceDTO = subDeviceService.getSubDeviceDTOById(id);
            if (subDeviceDTO != null) {
                response.put("success", true);
                response.put("data", subDeviceDTO);
                response.put("message", "获取分设备详情（包含Modbus配置）成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "分设备不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取分设备详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 创建分设备
     */
    @PostMapping
    @ApiOperation(value = "创建分设备", notes = "创建一个新的分设备")
    public ResponseEntity<Map<String, Object>> createSubDevice(
            @ApiParam(value = "分设备信息", required = true) @RequestBody SubDevice subDevice) {
        Map<String, Object> response = new HashMap<>();
        try {
            SubDevice createdSubDevice = subDeviceService.createSubDevice(subDevice);
            response.put("success", true);
            response.put("data", createdSubDevice);
            response.put("message", "创建分设备成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "创建分设备失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 更新分设备
     */
    @PutMapping("/{id}")
    @ApiOperation(value = "更新分设备", notes = "根据ID更新分设备信息")
    public ResponseEntity<Map<String, Object>> updateSubDevice(
            @ApiParam(value = "分设备ID", required = true) @PathVariable UUID id, 
            @ApiParam(value = "分设备信息", required = true) @RequestBody SubDevice subDevice) {
        Map<String, Object> response = new HashMap<>();
        try {
            SubDevice updatedSubDevice = subDeviceService.updateSubDevice(id, subDevice);
            response.put("success", true);
            response.put("data", updatedSubDevice);
            response.put("message", "更新分设备成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新分设备失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 删除分设备
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除分设备", notes = "根据ID删除分设备")
    public ResponseEntity<Map<String, Object>> deleteSubDevice(
            @ApiParam(value = "分设备ID", required = true) @PathVariable UUID id) {
        Map<String, Object> response = new HashMap<>();
        try {
            subDeviceService.deleteSubDevice(id);
            response.put("success", true);
            response.put("message", "删除分设备成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除分设备失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 批量删除分设备
     */
    @ApiOperation(value = "批量删除二级设备", notes = "根据ID列表批量删除二级设备")
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> deleteSubDevices(
            @ApiParam(value = "分设备ID列表", required = true) @RequestBody List<UUID> ids) {
        Map<String, Object> response = new HashMap<>();
        try {
            subDeviceService.deleteSubDevices(ids);
            response.put("success", true);
            response.put("message", "批量删除分设备成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量删除分设备失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 检查分设备ID是否存在
     */
    @GetMapping("/exists/{subDeviceId}")
    @ApiOperation(value = "检查分设备ID是否存在", notes = "检查分设备ID是否存在")
    public ResponseEntity<Map<String, Object>> checkSubDeviceIdExists(
            @ApiParam(value = "分设备ID", required = true) @PathVariable String subDeviceId) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean exists = subDeviceService.existsBySubDeviceId(subDeviceId);
            response.put("success", true);
            response.put("exists", exists);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查分设备ID失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取所有分设备
     */
    @GetMapping
    @ApiOperation(value = "获取所有分设备", notes = "获取所有分设备列表")
    public ResponseEntity<Map<String, Object>> getAllSubDevices() {
        Map<String, Object> response = new HashMap<>();
        try {
            List<SubDevice> subDevices = subDeviceService.getAllSubDevices();
            response.put("success", true);
            response.put("data", subDevices);
            response.put("message", "获取所有分设备成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取所有分设备失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}